package collection_try;
import java.util.*;

public class Comparable_Comparator implements Comparable<Comparable_Comparator>{
    private final Integer age;

    public Comparable_Comparator(Integer age) {
        this.age = age;
    }

    /** comparable
     * 返回一个int值，正数表示自己（this）比o大,0表示this=o2，负数表示this小于o2
     */
    @Override
    public int compareTo(Comparable_Comparator o) {
        //根据年龄决定谁大
        return o.age-this.age;
    /*
    *   this.age-o.age;
    *   2           1           3
    *   2-1=1       1-2=-1      3-2=1
    *   2-3=-1      1-3=-2      3-1=2
    *   1则会被视为小于其他对象从而排在前。
    *
    *   o.age-this.age;
    *   2           1           3
    *   1-2=-1      2-1=1       2-3=-1
    *   3-2=1       3-1=2       1-3=-2
    *   3则会被视为小于其他对象而排在前面。
    * */
    }

    @Override
    public String toString() {
        return "Comparable_Comparator{" +
                "age=" + age +
                '}';
    }

    public static void main(String[] args) {
        Comparable_Comparator test = new Comparable_Comparator(1);
        Comparable_Comparator test1 = new Comparable_Comparator(2);
        Comparable_Comparator test2 = new Comparable_Comparator(3);
        ArrayList<Comparable_Comparator> tests = new ArrayList<>();
        tests.add(test1);
        tests.add(test2);
        tests.add(test);
        System.out.println("list集合排序前"+Arrays.toString(tests.toArray())+"\n\n");
        System.out.println("==========Comparable排序===========");

        int i = test.compareTo(test1);
        System.out.println("Comparable：test和test1谁大（正数表示test大，0表示相等，负数表示test1大）"+i);
        Collections.sort(tests);
        System.out.println("list集合排序后"+Arrays.toString(tests.toArray())+"\n\n");


        System.out.println("==========Comparator排序===========");
//        Comparator<Comparable_Comparator> comparator = new Comparator<>() {
//            /**
//             * 返回一个int值，正数表示o2>o1,0表示o1=o2，负数表示o2小于o1
//             */
//            @Override
//            public int compare(Comparable_Comparator o1, Comparable_Comparator o2) {
//                //根据年龄决定谁大
//                return o2.age - o1.age;
//            }
//        };
//        int compare = comparator.compare(test, test1);
//        System.out.println("Comparator：test和test1谁大（正数表示test1大，0表示相等，负数表示test大）"+compare);

        //匿名类调用
        tests.sort(new Comparator<Comparable_Comparator>() {
            @Override
            public int compare(Comparable_Comparator o1, Comparable_Comparator o2) {
                return o1.age - o2.age;
            }
        });
        System.out.println("list集合排序后"+Arrays.toString(tests.toArray())+"\n\n");

        System.out.println("==========Lambda排序===========");
        tests.sort((o1, o2) -> o2.age - o1.age);
        System.out.println("lambda排序后"+Arrays.toString(tests.toArray())+"\n\n");
    }
}

